package usejava.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ListGroup2Map {

    class A {
        private String field1;
        private Integer field2;

        // 构造器
        public A(String field1, Integer field2) {
            this.field1 = field1;
            this.field2 = field2;
        }

        public String getField1() {
            return field1;
        }

        public void setField1(String field1) {
            this.field1 = field1;
        }

        public Integer getField2() {
            return field2;
        }

        public void setField2(Integer field2) {
            this.field2 = field2;
        }
    }

    /**
     * 对字段分组
     *
     * @param list
     * @return
     */
    public Map<String, List<Integer>> makeListGroup2Map(List<A> list) {
        Map<String, List<Integer>> map = list.stream()
                .collect(Collectors.groupingBy(
                        A::getField1, // 分组的键
                        Collectors.mapping(A::getField2, Collectors.toList()) // 映射到field2的列表
                ));
        return map;
    }

    public Map<String, List<A>> makeListGroupIdentity2Map(List<A> list) {
        Map<String, List<A>> map = list.stream()
                .collect(Collectors.groupingBy(A::getField1));
        return map;
    }
    public void printMap(Map<String, List<Integer>> map) {
        map.forEach((key, value) -> System.out.println(key + " : " + value));
    }
    public void print2Map(Map<String, List<A>> map) {
        map.forEach((key, value) -> System.out.println(key + " : " + value));
    }

    public List<A> makeList() {
        List<A> listA = Arrays.asList(
                new A("Key1", 1),
                new A("Key1", 2),
                new A("Key2", 3),
                new A("Key2", 4),
                new A("Key3", 5)
        );
        return listA;
    }
    public static void main(String[] args) {

        ListGroup2Map listGroup2Map = new ListGroup2Map();
        List<A> as = listGroup2Map.makeList();
        Map<String, List<Integer>> stringListMap = listGroup2Map.makeListGroup2Map(as);
        listGroup2Map.printMap(stringListMap);
        Map<String, List<A>> stringListMap1 = listGroup2Map.makeListGroupIdentity2Map(as);
        listGroup2Map.print2Map(stringListMap1);

    }


}
